package com.lanou.dormitory.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanou.dormitory.entity.Admin;
import com.lanou.dormitory.entity.Menu;
import com.lanou.dormitory.entity.Role;
import com.lanou.dormitory.service.AdminServic;
import com.lanou.dormitory.service.MenuService;
import com.lanou.dormitory.service.RoleMenuService;
import com.lanou.dormitory.service.RoleService;
import com.lanou.dormitory.util.EncryptUtil;
import com.lanou.dormitory.util.ResultUtil;

@Controller
public class AdminController {
	
	@Autowired
	private AdminServic adminService;
	@Autowired
	private RoleMenuService roleMenuService;
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private RoleService roleService;
	
	@RequestMapping("/admin/delAdminById/{id}")
	@ResponseBody
	public ResultUtil delete(@PathVariable Integer id){
		
		//根据这个id删除对应的数据
		adminService.deleteById(id);
		return ResultUtil.ok();
	}
	
	@RequestMapping("/admin/updAdmin")
	@ResponseBody
	public ResultUtil update(Admin admin){
		
		//根据admin中的id进行修改
		try {
			adminService.update2(admin);
			return ResultUtil.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error("修改失败");
		}
	}
	
	@RequestMapping("/admin/editAdmin/{adminId}")
	public String toEditAdmin(@PathVariable Integer adminId,
			HttpServletRequest request,HttpSession session){
		
		//需要把roles给获取到
		List<Role> roles = roleService.getAll();
		//在此处把 roles 放在session 或者 request 中
		session.setAttribute("roles", roles);
		
		//通过adminId查询出来admin相关信息在返回给jsp页面
		Admin admin = adminService.getAdminById(adminId);
		//admin相关的信息放在request范围
		request.setAttribute("admin", admin);
		return "/jsp/admin/editAdmin";
	}
	
	@RequestMapping("/admin/insAdmin")
	@ResponseBody
	public ResultUtil addAdmin(Admin admin){	
		//把密码使用MD5进行加密一下再入库
		String pwd = admin.getPassword();
		String md5pwd = EncryptUtil.encrypt(pwd);
		admin.setPassword(md5pwd);//admin对象中的密码就进行了MD5的加密处理
		//admin对象中包含了表单中的数据， 插入到数据库中
		try {
			adminService.addAdmin(admin);
			return ResultUtil.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error("添加失败");
		}
		
		
	}
	
	@RequestMapping("/admin/checkAdminName/{username}")
	@ResponseBody
	public ResultUtil checkName(@PathVariable String username){
		
		//根据username查询数据库，判断数据库中是否已存在此用户
		Admin admin = adminService.getQueryByUserName(username);
		if(admin==null){
			//用户名不存在
			return ResultUtil.ok();
		}else{
			//用户名存在
			return ResultUtil.error("用户名已存在");
		}
	}
	
	@RequestMapping("/admin/addAdmin")
	public String toAddAdmin(HttpSession session) {
		//需要把roles给获取到
				List<Role> roles = roleService.getAll();
				//在此处把 roles 放在session 或者 request 中
				session.setAttribute("roles", roles);
				return "/jsp/admin/addAdmin";//要跳转到admin的添加页面
	}
	
	@RequestMapping("/admin/getAdminList")
	@ResponseBody
	public ResultUtil getList(Integer page,Integer limit) {
		PageHelper.startPage(page, limit);
		List<Admin> list=adminService.getAll();
		PageInfo<Admin> info=new PageInfo<>(list);
		Long total=info.getTotal();
		List<Admin>pagelist=info.getList();
		ResultUtil result=new ResultUtil();
		result.setCode(0);
		result.setMsg("");
		result.setCount(total);
		result.setData(pagelist);
		return result;
		
	}
	
	@RequestMapping("/admin/adminList")
	public String toList(){
		return "/jsp/admin/adminList";
	}
	
	@RequestMapping("/admin/changeAdminPassword")
	@ResponseBody
	public ResultUtil changeAdminPassword(Integer admin_id,
			String username,String oldPassword,String newPassword1){
		
		//第一件事情判断老密码是否正确
		String oldMd5 = EncryptUtil.encrypt(oldPassword);
		Admin admin = adminService.login(username, oldMd5);
		if(admin!=null){
			//老密码是正确的
			//更新新的密码
			String newMd5 = EncryptUtil.encrypt(newPassword1);
			adminService.updatePwd(admin_id, newMd5);
			return ResultUtil.ok();
		}else{
			return ResultUtil.error("原始密码错误");
		}
			
	}
	
	@RequestMapping("/admin/changePassword")
	public String tochangePassword(){
		return "/jsp/admin/changePassword";
	}
	
	@RequestMapping("/admin/updateAdmin")
	@ResponseBody
	public ResultUtil updateAdmin(HttpSession session,Admin admin) {
		try {
			adminService.update(admin);
			session.setAttribute("admin1",admin);
			return ResultUtil.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.error("更新失败");
		}
	}
	
	
	@RequestMapping("/admin/personalDate")
	public String toPersonalInfo() {
		return "/jsp/admin/personalInfo";
	}
	
	@RequestMapping("/admin/getMenus")
	@ResponseBody
	public List<Menu> getMenus(HttpSession session){
		Admin admin = (Admin) session.getAttribute("admin");
		Long roleId = admin.getRoleId();//获取当前登录的角色ID
		
		//通过角色id 得到所有的菜单的ids
		List<Integer> menuIds = roleMenuService.getMenuIdsByRoleId(roleId);
		
		//通过所有的ids获取对应的菜单对象
		List<Menu> allMenus = menuService.getMenusByIds(menuIds);
		List<Menu> resultList =new ArrayList<>();
		for(int i=0;i<allMenus.size();i++) {
			Menu menu=allMenus.get(i);
			if(menu.getParentId()==0) {
				Long parentid= menu.getMenuId();
				List<Menu> children =new ArrayList<>();
				for(int j=0;j<allMenus.size();j++) {
					Menu cmenu=allMenus.get(j);
					if(cmenu.getParentId()==parentid) {
						children.add(cmenu);
					}
				}
				menu.setChildren(children);
				resultList.add(menu);
			}
			
		}
		
		return resultList;
	}
	
	@RequestMapping("/admin/allmain")
	public String toAllMain() {
		return "/jsp/allmain";
	}
	
	@RequestMapping("/admin/main")
	public String toMain() {
		return "/jsp/main";
	}
	
	@RequestMapping("/admin/login")
	@ResponseBody
	public ResultUtil login(HttpSession session,String username,String password){
		
		String md5pwd = EncryptUtil.encrypt(password);
		Admin admin = adminService.login(username, md5pwd);
		if(admin!=null){
			
			session.setAttribute("admin", admin);
			session.setAttribute("admin1", admin);
			
			ResultUtil result = new ResultUtil(0);
			return result;
		}else{
			ResultUtil result = new ResultUtil(5);
			return result;
		}
		
		
		
	}

}
